const { execSync } = require('child_process');
const fs = require('fs');
const path = require('path');

// 获取项目根目录
const rootDir = path.resolve(__dirname, '..');
process.chdir(rootDir);

console.log('===== 开始构建集成医疗诊断平台应用 =====');

// 检查Python环境
try {
  console.log('\n正在检查Python环境...');
  const pythonVersion = execSync('python --version').toString().trim();
  console.log(`检测到Python: ${pythonVersion}`);
} catch (error) {
  console.error('无法检测到Python环境，请确保Python已安装并添加到PATH中');
  process.exit(1);
}

// 安装依赖
try {
  console.log('\n正在安装Node.js依赖...');
  execSync('npm install', { stdio: 'inherit' });
} catch (error) {
  console.error('安装Node.js依赖失败:', error.message);
  process.exit(1);
}

// 打包Python应用
try {
  console.log('\n正在打包Python应用...');
  execSync('python scripts/build_python.py', { stdio: 'inherit' });
  
  const pythonAppPath = path.join(rootDir, 'dist', 'medical_api_server');
  const pythonExePath = path.join(pythonAppPath, 'medical_api_server.exe');
  
  if (!fs.existsSync(pythonAppPath)) {
    throw new Error('Python应用打包失败，未找到输出目录');
  }
  
  console.log(`Python应用输出目录: ${pythonAppPath}`);
  
  // 检查可执行文件是否存在
  if (!fs.existsSync(pythonExePath)) {
    console.warn(`警告: 找不到Python可执行文件 ${pythonExePath}`);
    console.log('检查dist/medical_api_server目录中的文件:');
    const files = fs.readdirSync(pythonAppPath);
    console.log(files);
  } else {
    console.log(`Python可执行文件已找到: ${pythonExePath}`);
  }
  
  // 手动创建输出目录结构并复制Python应用
  console.log('\n正在准备Python应用文件以供打包...');
  
  // 创建一个临时目录用于Electron打包
  const electronResourcesDir = path.join(rootDir, 'dist_electron_resources');
  const targetDir = path.join(electronResourcesDir, 'medical_api_server');
  
  // 确保目录存在
  if (!fs.existsSync(electronResourcesDir)) {
    fs.mkdirSync(electronResourcesDir, { recursive: true });
  }
  
  if (!fs.existsSync(targetDir)) {
    fs.mkdirSync(targetDir, { recursive: true });
  }
  
  // 复制Python应用到临时目录
  console.log(`正在复制Python应用文件从 ${pythonAppPath} 到 ${targetDir}`);
  const copyFiles = (src, dest) => {
    const entries = fs.readdirSync(src, { withFileTypes: true });
    
    entries.forEach(entry => {
      const srcPath = path.join(src, entry.name);
      const destPath = path.join(dest, entry.name);
      
      if (entry.isDirectory()) {
        if (!fs.existsSync(destPath)) {
          fs.mkdirSync(destPath, { recursive: true });
        }
        copyFiles(srcPath, destPath);
      } else {
        fs.copyFileSync(srcPath, destPath);
      }
    });
  };
  
  copyFiles(pythonAppPath, targetDir);
  console.log('Python应用文件复制完成');
  
} catch (error) {
  console.error('打包Python应用失败:', error.message);
  process.exit(1);
}

// 修改package.json的extraFiles配置
try {
  console.log('\n正在更新package.json配置...');
  const packageJsonPath = path.join(rootDir, 'package.json');
  const packageJson = require(packageJsonPath);
  
  // 更新extraFiles配置
  packageJson.build.extraFiles = [
    {
      "from": "dist_electron_resources/medical_api_server",
      "to": "resources/medical_api_server",
      "filter": ["**/*"]
    }
  ];
  
  // 更新extraResources配置，确保双重保障
  packageJson.build.extraResources = [
    {
      "from": "dist_electron_resources/medical_api_server",
      "to": "medical_api_server"
    }
  ];
  
  // 确保打包配置正确
  console.log('更新后的extraFiles配置:');
  console.log(JSON.stringify(packageJson.build.extraFiles, null, 2));
  console.log('更新后的extraResources配置:');
  console.log(JSON.stringify(packageJson.build.extraResources, null, 2));
  
  fs.writeFileSync(packageJsonPath, JSON.stringify(packageJson, null, 2));
  console.log('已更新package.json的配置');
} catch (error) {
  console.error('更新package.json配置失败:', error.message);
  process.exit(1);
}

// 修改Electron主进程启动Python应用的方式
try {
  console.log('\n正在修改Electron启动逻辑...');
  const mainJsPath = path.join(rootDir, 'electron', 'main.js');
  
  if (!fs.existsSync(mainJsPath)) {
    throw new Error('找不到electron/main.js文件');
  }
  
  // 跳过替换逻辑，保留用户手动修复的代码
  console.log('保留原始main.js文件，跳过自动替换');
  
  /*
  let mainJsContent = fs.readFileSync(mainJsPath, 'utf8');
  
  // 替换启动Python后端的逻辑
  const startPythonBackendLogic = `
function startPythonBackend() {
  // 检查Python后端是否已经在运行
  if (pythonProcess) {
    console.log('Python后端已经在运行');
    return;
  }

  try {
    let serverExecutable;
    let scriptPath;
    
    if (isDev) {
      // 开发环境：使用Python解释器
      const pythonExecutable = process.platform === 'win32' ? 'python' : 'python3';
      serverExecutable = pythonExecutable;
      scriptPath = path.join(app.getAppPath(), 'main.py');
      pythonProcess = spawn(serverExecutable, [scriptPath]);
    } else {
      // 生产环境：使用打包后的可执行文件
      const resourcesPath = process.resourcesPath;
      console.log('资源路径:', resourcesPath);
      
      // 查找打包后的服务器可执行文件
      if (process.platform === 'win32') {
        serverExecutable = path.join(resourcesPath, 'medical_api_server', 'medical_api_server.exe');
      } else {
        serverExecutable = path.join(resourcesPath, 'medical_api_server', 'medical_api_server');
      }
      
      console.log(\`服务器可执行文件路径: \${serverExecutable}\`);
      
      if (!fs.existsSync(serverExecutable)) {
        throw new Error(\`找不到服务器可执行文件: \${serverExecutable}\`);
      }
      
      // 启动打包后的服务器
      pythonProcess = spawn(serverExecutable);
    }
    
    pythonProcess.stdout.on('data', (data) => {
      console.log(\`Python后端输出: \${data}\`);
    });
    
    pythonProcess.stderr.on('data', (data) => {
      console.error(\`Python后端错误: \${data}\`);
    });
    
    pythonProcess.on('close', (code) => {
      console.log(\`Python后端进程退出，退出码 \${code}\`);
      pythonProcess = null;
    });

    // 等待后端启动
    waitForBackendReady();
  } catch (error) {
    console.error('启动Python后端失败:', error);
    showErrorDialog('启动失败', \`无法启动Python后端服务: \${error.message}\`);
  }
}`;

  // 替换函数
  mainJsContent = mainJsContent.replace(/function startPythonBackend\(\) \{[\s\S]*?waitForBackendReady\(\);[\s\S]*?\}/m, startPythonBackendLogic);
  
  // 修复可能存在的双重catch块问题
  mainJsContent = mainJsContent.replace(/\} catch \(error\) \{[\s\S]*?showErrorDialog\([^\)]+\);[\s\S]*?\}(\s*)\} catch/m, '} catch');
  
  fs.writeFileSync(mainJsPath, mainJsContent);
  */
  
  console.log('已修改Electron启动逻辑');
} catch (error) {
  console.error('修改Electron启动逻辑失败:', error.message);
  process.exit(1);
}

// 构建Electron应用
try {
  console.log('\n正在验证Python应用准备状态...');
  const resourcesDir = path.join(rootDir, 'dist_electron_resources', 'medical_api_server');
  
  if (!fs.existsSync(resourcesDir)) {
    throw new Error('无法找到Python应用临时目录，打包准备不完整');
  }
  
  // 列出临时目录内容
  console.log('Python应用临时目录内容:');
  const files = fs.readdirSync(resourcesDir);
  console.log(files);
  
  if (!files.includes('medical_api_server.exe')) {
    throw new Error('Python应用临时目录中缺少可执行文件');
  }
  
  console.log('Python应用准备就绪，开始构建Electron应用...');
  execSync('npm run electron:build', { stdio: 'inherit' });
} catch (error) {
  console.error('构建Electron应用失败:', error.message);
  process.exit(1);
}

console.log('\n===== 构建完成 =====');
console.log('应用已打包到 dist_electron 目录'); 